﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using Microsoft.ApplicationBlocks.Data;

namespace MyTemplate
{
    public partial class ArticleListPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.GetCustomersPageWise(1);
            }
        }

        protected void PageSize_Changed(object sender, EventArgs e)
        {
            this.GetCustomersPageWise(1);
        }

        private void GetCustomersPageWise(int pageIndex)
        {
            string constring = SqlHelper.DbConnectionString;

            SqlConnection connection = new SqlConnection(SqlHelper.DbConnectionString);
            SqlCommand command = null;
            SqlDataReader reader = null;

            connection.Open();
            command = new SqlCommand("spGetArticlesPage", connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@PageIndex", pageIndex);
            command.Parameters.AddWithValue("@PageSize", int.Parse(ddlPageSize.SelectedValue));
            command.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
            command.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
            reader = command.ExecuteReader();



            GridView1.DataSource = reader;
            GridView1.DataBind();

            reader.Close();

            int recordCount = Convert.ToInt32(command.Parameters["@RecordCount"].Value);
            this.PopulatePager(recordCount, pageIndex);

            connection.Close();


        }

        protected void Page_Changed(object sender, EventArgs e)
        {
            int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
            this.GetCustomersPageWise(pageIndex);
        }

        private void PopulatePager(int recordCount, int currentPage)
        {
            double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
            int pageCount = (int)Math.Ceiling(dblPageCount);
            List<ListItem> pages = new List<ListItem>();
            if (pageCount > 0)
            {
                pages.Add(new ListItem("First", "1", currentPage > 1));
                for (int i = 1; i <= pageCount; i++)
                {
                    pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                }
                pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
            }
            rptPager.DataSource = pages;
            rptPager.DataBind();
        }
    }
}